package com.xlongwei.accounts.config;

import java.util.Properties;
import org.noear.redisx.RedisClient;
import org.noear.redisx.plus.RedisBus;
import org.noear.solon.Solon;
import org.noear.solon.cache.jedis.RedisCacheService;
import org.noear.solon.core.event.AppStopEndEvent;
import org.noear.solon.data.cache.CacheService;
import org.noear.solon.data.cache.impl.JsonSerializer;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.solon.dao.SaTokenDaoOfRedis;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RedisConfig {
    public static RedisClient client;
    public static RedisBus bus;

    public static void init() {
        if (!AppConfig.enableRedis) {
            return;
        }
        Properties props = Solon.cfg().getProp("redis");
        log.info("redis.props={}", props);
        client = new RedisClient(props);
        bus = client.getBus();
        Solon.app().onEvent(AppStopEndEvent.class, e -> client.close());
        // 分布式部署需配置-Daccounts.enableRedis=true启用redis，sa-token认证数据保存到redis
        SaTokenDao saTokenDao = new SaTokenDaoOfRedis(client);
        SaManager.setSaTokenDao(saTokenDao);
    }

    public static CacheService cacheService(String mobile) {
        RedisCacheService cacheService = new RedisCacheService(client, mobile, AppConfig.defSeconds);
        cacheService.enableMd5key(false);
        cacheService.serializer(JsonSerializer.typedInstance);
        return cacheService;
    }
}
